import { Body, Controller, Get, Param,Post,Put,Delete, UseInterceptors, BadRequestException, UploadedFile, Query } from '@nestjs/common';
import { BookService } from './book.service';
import { CreateBookDto } from './dto/create-book.dto';
import { UpdateBookDto } from './dto/update-book.dto';
import * as path from 'path';
import { FileInterceptor } from '@nestjs/platform-express';
import { storage } from './my-file-storage';

@Controller('book')
export class BookController {
  constructor(private readonly bookService: BookService) {}

  @Post('upload')
  @UseInterceptors(FileInterceptor('file',{
    dest: 'uploads',
    storage,
    limits:{
      fileSize: 1024 * 1024 * 3, // 3MB
    },
    fileFilter(req,file,callback){
      const extname = path.extname(file.originalname); // 获取文件拓展名
      if(['.png','.jpg','.jpeg','.gif','.bmp'].includes(extname)){
        callback(null,true);
      }else{
        callback(new BadRequestException('只能上传图片'),false);
      }
    }
  }))
  uploadFile(@UploadedFile() file: Express.Multer.File){
    return file.path;
  }
  @Get('list')
  async list(@Query('name') name:string) {
    return await this.bookService.list(name);
  }
  @Get(':id')
  async findById(@Param('id') id: string) {
    return await this.bookService.findById(+id);
  }

  @Post('create')
  async create(@Body() createBookDto: CreateBookDto) {
    return await this.bookService.create(createBookDto);
  }
  @Put('update')
  async update(@Body() updateBookDto: UpdateBookDto) {
    return await this.bookService.update(updateBookDto);
  }

  @Delete('delete/:id')
  async delete(@Param('id') id: string) {
    return await this.bookService.delete(+id);
  }



}
